<template>
  <div class="app-container" style="height: 100%">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="100px">
      <el-form-item label="物料编码" prop="productNo">
        <el-input
          v-model="queryParams.productNo"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料类型" prop="productType">
        <el-select v-model="queryParams.productType" placeholder="请选择物料类型"  >
          <el-option
            v-for="dict in dict.type.basic_product_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="btnGroup">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:bom:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:bom:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="orderScrap"
          v-hasPermi="['basic:bom:scrap']"
        >作废</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:bom:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['basic:bom:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:bom:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange" :height="calcTableHeight"
              highlight-current-row @current-change="rowSelection" >
      <el-table-column type="selection" width="55" align="center" />
      <af-table-column label="物料编码" align="center" prop="productNo" />
      <af-table-column label="物料名称" align="center" prop="productName" />
      <af-table-column label="物料类型" align="center" prop="productType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.basic_product_type" :value="scope.row.productType"/>
        </template>
      </af-table-column>
      <af-table-column label="BOM版本" align="center" prop="bomVersion" />
      <af-table-column label="BOM类型" align="center" prop="bomType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.basic_bom_type" :value="scope.row.bomType"/>
        </template>
      </af-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.basic_bom_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" min-width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="152"/>
      <el-table-column label="最后更新人" align="center" prop="updateBy" min-width="100"/>
      <el-table-column label="最后更新时间" align="center" prop="updateTime" width="152"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--   单据明细 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
      <el-tab-pane label="BOM组件" name="detailList">
        <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改物料BOM对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="物料" prop="productNo">
          <el-select @change="changeProduct" style="width:100%;" v-model.trim="form.productNo" filterable placeholder="请选择物料">
            <el-option
              v-for="dict in productList"
              :key="dict.productNo"
              :label="dict.productName + '（' + dict.productNo + '）'"
              :value="dict.productNo"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="BOM类型" prop="bomType">
          <el-select @change="changeBomType" style="width:100%;" v-model.trim="form.bomType" placeholder="请选择BOM类型"  >
            <el-option
              v-for="dict in dict.type.basic_bom_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="BOM版本" prop="bomVersion">
          <el-input v-model.trim="form.bomVersion" placeholder="请输入BOM版本" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixin/pageSearchTable";
import { getBomPage, getBonInfo, delBomInfo, addBomInfo, updateBomInfo, scrapBom } from "./api/productBom";
import { listProduct} from "@/api/basic/product";
import { getToken } from "@/utils/auth";
import detailPage from "../bomDetail/index";

export default {
  name: "productBom",
  dicts: ['basic_product_type','basic_bom_type','basic_bom_status'],
  mixins:[mixins],
  components: { detailPage },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      selectionRows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单据表格数据
      bomList: [],
      // 物料列表
      productList: [],
      // 物料列表
      bomTypeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        orderType: 1,
        orderStatus: null,
        customerNo: null,
        customerName: null,
        workOrderNo: null,
        createUser: null,
        updateUser: null,
        sort: null
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/bom/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productNo: [
          { required: true, message: "请选择物料", trigger: "change" }
        ],
        bomType: [
          { required: true, message: "请选择BOM类型", trigger: "change" }
        ],
        bomVersion: [
          { required: true, message: "请输入BOM版本", trigger: "blur" }
        ],
      },
      //页面下方明细的选项
      activeTab:'detailList',
      //传递给订单详情的数据
      orderData:{}
    };
  },
  created() {
    this.getListCustomer();
    this.getList();
  },
  methods: {
    handleTabClick(value){
      console.log(value)
    },
    getListCustomer(){
      listProduct({pageNum:1,pageSize:0}).then(response => {
        this.productList = response.rows;
      });
    },
    /** 查询单据列表 */
    getList() {
      this.loading = true;
      this.rowSelection({});
      getBomPage(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 修改物料
    changeProduct(){
      const product = this.productList.find(item => item.productNo === this.form.productNo)
      this.$set(this.form,'productType',product.productType);
      this.$set(this.form,'productName',product.productName);
    },
    changeBomType(){
      this.$refs.form.clearValidate('bomType');
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,'queryParams',{});
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.nos = selection.map(item => item.no)
      this.single = selection.length!==1
      this.selectionRows = selection
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增BOM";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (this.selectionRows[0].status == 'SCRAP'){
        this.$modal.msgWarning("该状态无法编辑")
        return;
      }
      this.reset();
      const id = row.id || this.ids
      getBonInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BOM";
      });
    },
    /** 作废按钮操作 */
    orderScrap(row) {
      if (this.selectionRows[0].status == 'SCRAP'){
        this.$modal.msgWarning("该状态无法报废")
        return;
      }
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认将选中的数据作废？').then(function() {
        return scrapBom(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBomInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBomInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const nos = row.no || this.nos;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delBomInfo(nos);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/bom/export', {
        ...this.queryParams, ids: this.ids
      }, `物料BOM_${new Date().getTime()}.xlsx`)
    },
    //行选择
    rowSelection(row){
      this.orderData = row;
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料BOM导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
        const a = document.createElement('a');

        a.href = `${process.env.BASE_URL}static/file/物料BOM导入模板.xlsx` //'./static/file/物料BOM导入模板.xlsx';
        a.click();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
